package cn.gok.tech.springboot_face.entriy;

import com.baidu.aip.face.AipFace;
import org.json.JSONObject;
import org.springframework.stereotype.Component;
import sun.misc.BASE64Encoder;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.HashMap;

@Component
public class Face {
    //设置APPID/AK/SK
    public static final String APP_ID = "17175702";
    public static final String API_KEY = "QAvdKUxWRGWGQQQkoiBfELnG";
    public static final String SECRET_KEY = "Eg1gCMDCunwwZeBoGoG7ay8SIGpUQmcF";

    AipFace client=null;

    public Face(){
        // 初始化一个AipFace
        client = new AipFace(APP_ID, API_KEY, SECRET_KEY);

        // 可选：设置网络连接参数
        client.setConnectionTimeoutInMillis(2000);
        client.setSocketTimeoutInMillis(6000);
    }

    public String getFaceInfo(String imagebase64){
        HashMap<String, String> options = new HashMap<String, String>();
//         options.put("face_field", "age");
          options.put("max_face_num", "5");
//         options.put("face_type", "LIVE");
//         options.put("liveness_control", "LOW");

//        String image = this.imageToBase64("E:\\SSM项目\\Springboot_FaceOCRTest\\src\\main\\resources\\static\\3.jpg");
          String image=imagebase64;
        String imageType = "BASE64";

        // 人脸检测
        JSONObject res = client.detect(image, imageType, options);
        return res.toString();
    }



    /*
     * 将本地图片转为BASE64方法
     */
    public static String imageToBase64(String imgPath) {
        InputStream in = null;
        byte[] data = null;
        // 读取图片字节数组
        try {
            in = new FileInputStream(imgPath);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        //对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        //返回Base64编码的字节数组字符串
        return encoder.encode(data);
    }



}
